/*
 * Copyright 2007 Netflix, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.oauth.example.consumer.webapp;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.oauth.OAuthAccessor;
import net.oauth.OAuthConsumer;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.ycy.ss.Constant;
import com.ycy.ss.status.AllStatus;
import com.ycy.ss.status.StatusTumblr;
import com.ycy.ss.tumblr.TumblrUtil;
import com.ycy.ss.tumblr.po.TumblrPostBase;


/**
 * A trivial consumer of the 'friends_timeline' service at Twitter.
 * 
 * @author John Kristian
 */
public class TumblrConsumer extends HttpServlet{
	private Logger logger = LogManager.getLogger(TumblrConsumer.class);

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
		if ("1".equals(request.getParameter("clear"))) {
			AllStatus.tumblr = null;
			response.getWriter().write("clear");
			return;
		}

		OAuthConsumer consumer = null;
		try {
			consumer = CookieConsumer.getConsumer("tumblr", getServletContext());
			OAuthAccessor accessor = CookieConsumer.getAccessor(request, response, consumer);

			StatusTumblr statusTumblr = new StatusTumblr();
			statusTumblr.ACCESS_TOKEN = accessor;

			Map<String, String> paramMap = new HashMap<String, String>();
			paramMap.put("limit", "5");
			paramMap.put("filter", "text");
			
			List<TumblrPostBase> tumblrPostBaseList = TumblrUtil.queryPosts(accessor, Constant
					.getAccountInfo("tumblr.baseHostname"), paramMap);
			if (tumblrPostBaseList != null && tumblrPostBaseList.size() != 0) {
				statusTumblr.readOk(tumblrPostBaseList.get(0).getDate() + "");
			} else {
				statusTumblr.readOk("");
			}

			AllStatus.tumblr = statusTumblr;
			response.getWriter().write("ok");

		} catch (Exception e) {
			CookieConsumer.handleException(e, request, response, consumer);
		}
	}

	private static final long serialVersionUID = 1L;

}
